#include "reactor/tcp_server.h"
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

using namespace std;

class CHandle : public ITcpEvent {
protected:
    virtual void OnConnect(TcpServer& server, IHandle* h) {}

    virtual void OnRead(TcpServer& server, IHandle* h, const char* buf, int len) {
        for (int i = 0; i < len; ++i) {
            printf("%c", buf[i]);
        }
        printf("\n----------[%lld]---------- %d byte got\n", h, len);
        server.Write(h, buf, len);
    }

    virtual void OnDisconnect(TcpServer& server, IHandle* h) {}

    virtual void OnServerLog(TcpServer& server, const std::string& log) {
        printf("%s\n", log.c_str());
    }

    virtual void OnClientLog(TcpServer& server, IHandle* h, const std::string& log) {
        printf("[%lld] %s\n", h, log.c_str());
    }
};

int main(int argc, char* argv[]) {
    if (argc != 3) {
        printf("argc error\n");
        return -1;
    }

    sigset_t new_set, old_set;
    sigemptyset(&new_set);
    sigaddset(&new_set, SIGTERM);
    sigaddset(&new_set, SIGINT);
    sigprocmask(SIG_BLOCK, &new_set, &old_set);

    CHandle handle;
    TcpServer server(&handle, 5);
    auto ret = server.Init(argv[1], atoi(argv[2]));
    if (!get<0>(ret)) {
        printf(get<1>(ret).c_str());
        return -1;
    }

    sigset_t sig_pending;
    while (1) {
        server.HandleEvents(3);

        sigemptyset(&sig_pending);
        sigpending(&sig_pending);
        if (sigismember(&sig_pending, SIGTERM)) {
            break;
        } else if (sigismember(&sig_pending, SIGINT)) {
            break;
        }
    }
    return 0;
}
